<template>
  <div class="sn-common-container ">
    <div class="prcoss-container">
      <header>
        <div class="sn-flex sn-row-center hidden-sm-and-down">
          <el-input v-model="searchValue" placeholder="输入员工名称进行筛选" style="width: 200px" clearable
            @keyup.enter.native="currentChange(1)" />
          <el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-search"
            @click="currentChange(1)">
            搜索
          </el-button>
          <el-button class="sn-btn" style="margin-left: 10px" type="primary" icon="el-icon-plus"
            @click="getTreeDataFn()">
            调整员工上下级
          </el-button>
          
        </div>
        <div class="hidden-sm-and-up">
          <el-input v-model="searchValue" placeholder="输入员工名称进行筛选" style="width: 200px" clearable
            @keyup.enter.native="currentChange(1)" />
          <el-button style="margin-left: 4px" type="primary" class="sn-btn" icon="el-icon-search"
            @click="currentChange(1)">
            搜索
          </el-button>

        </div>
      </header>
      <section>
        <global-table style="margin-top: 20px;" :pageIndex="currentPage" :pageSize="pageSize" :headerData="initData"
          :data="tabelData" :isFullScreen="false" :operateW="200">
          <template #roles="scope" >
            <div style="width: 100%;overflow: hidden;flex-wrap: wrap;flex:1;" class="sn-flex">
              <span v-if="scope.row.roles.length===0">无</span>
              <el-tag v-for="(item,index) in scope.row.roles" :key="index" style="margin: 2px;">{{item.name}}</el-tag>
            </div>
          </template>
          <template #operate="scope">
            <el-button type="primary"  size="mini" @click="editStaffBtnClick(scope.row)">修改</el-button>
            <el-button type="primary" class="sn-btn" icon="el-icon-delete" size="mini" @click="delStaffFn(scope.row.userId)">删除</el-button>
          </template>
        </global-table>
      </section>
      <footer style="margin-top: 20px;">
        <el-pagination @current-change="currentChange" :current-page.sync="currentPage" :page-size="pageSize"
          layout="prev, pager, next, jumper" :pager-count="7" class="sn-pagination" hide-on-single-page
          style="text-align: center;" :total="totalNum" background>
          >
        </el-pagination>
      </footer>
      
    </div>
    <!-- 编辑或新增弹窗 -->
    <el-dialog :visible.sync="editStaffDialog" class="sn-default-dialog" width="360px" @close="roleDialogClose()">
      <div class="sn-title" slot="title">编辑员工</div>
      <div v-loading="editStaffLoading">
        <p style="margin-top: 0;">员工名称：</p>
        <el-input v-model="editStaffName" placeholder="请输入员工名称" style=""></el-input>
        <p >员工手机号：</p>
        <el-input v-model="editStaffPhone" placeholder="请输入员工手机号" style=""></el-input>
        <p>关联角色：</p>
        <el-checkbox-group v-model="roleIds">
          <el-checkbox  border  v-for="(item) in roleList" :key="item.id" :label="item.id" style="margin: 3px;">{{ item.name }}</el-checkbox>
        </el-checkbox-group>
        <p style="text-align: center;">
          <el-button type="primary" size="medium" class="sn-btn" @click="saveRoleInfoFn()">保存</el-button>
          <el-button size="medium" @click="editStaffDialog = false">取消</el-button>
        </p>
      </div>
    </el-dialog>
    <!-- 编辑或新增弹窗 -->
    <el-dialog :visible.sync="employeeDialog" class="sn-default-dialog" width="360px" @close="roleDialogClose()">
      <div class="sn-title" slot="title">调整员工上下级</div>
      <div >
        <el-tree
        :data="treeData"
        v-loading="treeLoading"
        :props="defaultProps"
        node-key="userId"
        default-expand-all
        @node-drop="handleDrop"
        draggable
       >
      </el-tree>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import GlobalTable from '@/components/GlobalTable';
import {GetEmployeePage, UpdateEmployee,DeleteEmployee,GetRoles,GetEmployeeTree,SetEmployeeParent } from '@/api/accessmanage';
import { guid } from '@/utils'
export default {
  components: { GlobalTable },
  data() {
    return {
      tabelData: [],
      treeData:[],
      initData: [
        {
          label: '员工名称',
          value: 'employeeName',
          id: guid(),
        },
        {
          label: '手机号',
          value: 'mobile',
          id: guid(),
        },
        {
          label: '关联角色',
          value: 'roles',
          id: guid(),
          isCustom:true,
          width:300
        },
        
      ],
      currentPage: 1,
      pageSize: 10,
      totalNum: 0,
      searchValue: '',
      editStaffDialog: false,
      editStaffName: '',
      editStaffPhone:'',
      userTags: [],
      addEmployeeFlag: true,
      staffLoadingFlag: false,
      searchEmployeeName: '',
      editStaffLoading: false,
      staffId: '',
      roleIds:[],
      roleList:[],
      defaultProps: {
        children: 'children',
        label: 'employeeName',
      },
      treeLoading:false,
      employeeDialog:false
    }
  },
  created() {
    this.getDataListFn();
  },
  methods: {
    // 拖拽员工
   async handleDrop(current,targetItem,type){
      let params = {
        id:current.key,
        parentId:targetItem.key
      }
      if(type!=='inner'){
        if(targetItem.level === 1){
         params.parentId = null;
        }else{
         params.parentId = targetItem.parent.key;
        }
      }
      try {
          this.treeLoading = true;
          const res = await SetEmployeeParent(params);
          this.treeLoading = false;
          if(res.code !== 200){
            this.$message.error(res.erroMessage);
          }else{
            this.getTreeDataFn();
          }
        } catch (error) {
          this.getTreeDataFn();
        }
    },
    // 获取员工树
    async getTreeDataFn(){
      const res = await GetEmployeeTree();
      if(res.code=== 200){
        this.treeData = res.data;
        this.employeeDialog = true;
      }else{
        this.$message.error(res.erroMessage);
      }
    },
    delStaffFn(id){
      this.$confirm('您将要删除该员工, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          this.loading = true;
          try {
             let res = await DeleteEmployee({id:id});
             this.loading = false;
             if(res.code === 200){
                this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getDataListFn();
             }else{
               this.$message.error('删除失败，错误信息：'+res.erroMessage);
             }
          } catch (error) {
            this.loading = false;
            this.erroMessageShow(error);
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });  
        });
    },
    // 保存员工基本信息
    async saveRoleInfoFn() {
      this.editStaffLoading = true;
      let params = {
        userId:this.staffId,
        employeeName:this.editStaffName,
        mobile:this.editStaffPhone,
        roleIds:this.roleIds
      }
        let res = await UpdateEmployee(params);
        this.editStaffLoading = false;
        if (res.code === 200) {
          this.$message.success('修改员工信息成功');
          this.editStaffDialog  = false;
          this.getDataListFn();
        } else {
          this.$message.error('修改员工失败，错误信息：' + res.erroMessage)
        }
    },
    // 关闭编辑员工信息窗口
    roleDialogClose() {
      this.editStaffName = '';
      this.editStaffPhone = '';
      this.roleIds = [];
      this.editStaffLoading = false;
      this.staffId ='';
    },
    async editStaffBtnClick(data) {
      this.editStaffDialog = true;
      this.editStaffLoading = true;
      this.staffId = data.userId;
      this.editStaffName = data.employeeName;
      this.editStaffPhone = data.mobile;
      this.roleIds = data.roles.map(item=>{
        return item.id
      })
      let res = await GetRoles();
      this.editStaffLoading = false;
      if (res.code === 200) {
        this.roleList = res.data;
      } else {
        this.$message.error('获取员工对应权限失败，错误信息：' + res.erroMessage)
      }
    },
    currentChange(val) {
      this.currentPage = val;
      this.getDataListFn();
    },
    async getDataListFn() {
      let params = {
        pageIndex: this.currentPage,
        pageSize: this.pageSize,
        EmployeeName: this.searchValue
      }
      const res = await GetEmployeePage(params);
      if (res.code === 200) {
        this.tabelData = res.data.list;
        this.totalNum = res.data.totalCount;
      } else {
        this.tabelData = [];
        this.$message.error('获取员工列表失败，错误信息：' + res.erroMessage);
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.prcoss-container {
  box-sizing: border-box;
  padding: 20px;
  background-color: #fff;
}
</style>